package top.sqdpt.file.factory;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.sqdpt.file.enums.FileStorageType;
import top.sqdpt.file.strategy.FileStorageStrategy;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class FileStorageFactory implements InitializingBean {
    @Value("${aichat.file.storage.type:LOCAL}")
    private FileStorageType fileStorageType = FileStorageType.LOCAL;

    @Autowired
    private List<FileStorageStrategy> fileStorageStrategyList;

    private Map<FileStorageType, FileStorageStrategy> fileStorageStrategyMap;

    @Override
    public void afterPropertiesSet() {
        if(fileStorageStrategyList == null){
            throw new IllegalStateException("未配置存储策略类");
        }
        fileStorageStrategyMap = fileStorageStrategyList.stream()
                .collect(Collectors.toMap(FileStorageStrategy::getFileStorageType, x -> x, (a, b) -> {
            throw new IllegalStateException("存储策略类型存在多个实现类：" + a.getFileStorageType());
        }));
    }

    /**
     * @return 获取系统配置存储策略
     */
    public FileStorageStrategy getFileStorageStrategy() {
        FileStorageStrategy strategy = fileStorageStrategyMap.get(fileStorageType);
        if (strategy == null) {
            throw new IllegalStateException("没有找到对应的存储策略:" + fileStorageType);
        }
        return strategy;
    }


}
